package JzOffer.jz60;

import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

// 有bug
public class Solution01 {
	public int[] topKFrequent(int[] nums, int k) {
		HashMap<Integer, Integer> map1 = new HashMap<>();
		TreeMap<Integer, Integer> map2 = new TreeMap<>(
				new Comparator<Integer>() {
					@Override
					public int compare(Integer e1, Integer e2) {
						return -e1.compareTo(e2);
					}
				});

		for (int i = 0; i < nums.length; i++) {
			map1.put(nums[i], map1.getOrDefault(nums[i], 0) + 1);
			// 按出现频率逆序插入到map中
			map2.put(map1.get(nums[i]), nums[i]);
			System.out.println(map1.get(nums[i]) + ", " + nums[i]);
		}

		System.out.println("-------------------");
		Set<Integer> keys = map2.keySet();
		Iterator<Integer> iterator = keys.iterator();
		while (iterator.hasNext()) {
			Integer key = iterator.next();
			System.out.println(key + ", " + map2.get(key));
		}

		int[] res = new int[k];
		int i = 0;
		Collection<Integer> values = map2.values();
		for (Integer value : values) {
			if (i < k) {
				res[i] = value;
				i++;
			} else {
				break;
			}
		}

		return res;
	}
}
